package demo.dao;

import jdbc.DBUtil;
import jdbc.UserInfo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserMapper1 {
    public UserInfo findByUsername(String username){
        try(Connection conn = DBUtil.getConnection()) {
            PreparedStatement ps = conn.prepareStatement("SELECT username,password,nickname,age FROM userinfo WHERE username = ?");
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                UserInfo user = new UserInfo();
                user.setUsername(username);
                user.setPassword(rs.getString("password"));
                user.setNickname(rs.getString("nickname"));
                user.setAge(rs.getInt("age"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public int update(UserInfo user){
        try(Connection conn = DBUtil.getConnection()) {
            PreparedStatement ps = conn.prepareStatement("UPDATE userinfo SET password = ?, nickname = ?,age = ? WHERE username = ?");
            ps.setString(1,user.getPassword());
            ps.setString(2,user.getNickname());
            ps.setInt(3,user.getAge());
            ps.setString(4,user.getUsername());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
       return 0;
    }
}
